package com.cypher.encryptionanddecryption.fragment.protocol.kunlun;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.fragment.protocol.AbstractProtocolFragment;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.KunLunProtocolUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 昆仑只读界面
 * @author: 古霸天
 * @date: 2020/11/16
 */
public class ReadonlyFragment extends AbstractProtocolFragment {
    private Context context;
    private CommunicationBean bean;
    private EditText commResult;
    public ReadonlyFragment(Context context, CommunicationBean bean) {
        this.context = context;
        this.bean = bean;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_kunlun_readonly, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        commResult = view.findViewById(R.id.comm_result);
    }

    @Override
    public void fillFragment(String data) {
        // 每次渲染时清空控件
        commResult.setText("");

        // 程序暂停0.2秒后开始渲染数据
        Runnable r = () -> {
            // 读表号
            String formatData = KunLunProtocolUtils.formatReceiveData(data);
            switch (bean.getHexCode()) {
                case "00B0830008" : // 读表号
                    commResult.setText("表号：" + StringUtils.substring(formatData, 6));
                    break;
                case "030120FD" : // 读IMEI
                    formatData = StringUtils.substring(formatData, 8, 16 + 8);
                    if (StringUtils.equals("0", StringUtils.substring(formatData, 0, 1))) {
                        formatData = StringUtils.substring(formatData, 1);
                    }

                    commResult.setText("IMEI：" + formatData);
                    break;
                case "00B0840049" : // 读参数
                    commResult.setText(renderParam(StringUtils.substring(formatData, 6)));
                    break;
                case "030110FF" : // 读状态
                    commResult.setText(readerState(formatData));
                    break;
                case "030110FE" : // 读温补数据
                    commResult.setText(readerRemovingData(formatData));
                    break;
                case "030220FF20FE" : // 读版本/锂电电压
                    commResult.setText(readerLithiumVoltage(formatData));
                    break;
                case "00D691040100" : // 清除E-1错误
                    commResult.setText(readerClearE1Error(formatData));
                    break;
                default:
                    commResult.setText(bean.getName() + "：");
            }
        };
        new Handler().postDelayed(r, 200);

    }

    @Override
    public String getHexCode(String rwType) {
        if (StringUtils.equals("true", bean.getSpecial())) {
            return KunLunProtocolUtils.getKunLunSpecialCommand(bean.getHexCode());
        }
        // 组包
        return KunLunProtocolUtils.getKunLunCommand(bean.getHexCode());
    }

    /**
     * 根据接收数据渲染昆仑协议参数
     * @param data
     * @return
     */
    private String renderParam(String data) {
        StringBuffer result = new StringBuffer();

        fullBuf(result, "注册报文密钥信息：", StringUtils.substring(data, 0, 12));

        String ipHex = StringUtils.substring(data, 12, 14);
        String ipTitle;
        if (StringUtils.equals("00", ipHex)) ipTitle = "IPV4";
        else if (StringUtils.equals("01", ipHex)) ipTitle = "IPV6";
        else ipTitle = ipHex;
        fullBuf(result, "IP地址版本：", ipTitle);

        String ipV4AddressHex = StringUtils.substring(data, 14, 22);
        String ipV4AddressTitle;
        if (StringUtils.equals("B4659373", ipV4AddressHex)) ipV4AddressTitle = "180.101.147.115(测试平台)";
        else if (StringUtils.equals("753C9D89", ipV4AddressHex)) ipV4AddressTitle = "117.60.157.137(正式平台)";
        else ipV4AddressTitle = ipV4AddressHex;
        fullBuf(result, "IPV4地址：", ipV4AddressTitle);

        String ipV6AddressHex = StringUtils.substring(data, 22, 54);
        fullBuf(result, "IPV6地址：", "0:0:0:0:0:0:0:0");

        fullBuf(result, "端口号：", Integer.parseInt(StringUtils.substring(data, 54, 58), 16));

        fullBuf(result, "APN：", HexUtils.ascToStr(StringUtils.substring(data, 58, 118)));

        String periodTypeHex = StringUtils.substring(data, 118, 120);
        String periodTypeTitle;
        if (StringUtils.equals("00", periodTypeHex)) periodTypeTitle = "天";
        else if (StringUtils.equals("01", periodTypeHex)) periodTypeTitle = "月";
        else periodTypeTitle = periodTypeHex;
        fullBuf(result, "定时上传周期类型：", periodTypeTitle);

        fullBuf(result, "定时上传周期值：", Integer.parseInt(StringUtils.substring(data, 120, 122), 16));

        fullBuf(result, "定时上传时间点：", StringUtils.substring(data, 122, 126));

        fullBuf(result, "一级多天不用气关阀门限：", Integer.parseInt(StringUtils.substring(data, 126, 128), 16));
        fullBuf(result, "二级多天不用气关阀门限：", Integer.parseInt(StringUtils.substring(data, 128, 130), 16));

        String closeValveParamTitle = "开启";
        if (StringUtils.equals("00", data.substring(130, 132))) closeValveParamTitle = "禁用";
        fullBuf(result, "多天不通信关阀参数：", closeValveParamTitle);

        fullBuf(result, "过流报警关阀使能：", enableFormat(data.substring(132, 134)));

        double overThreshold = (double) Integer.parseInt(StringUtils.substring(data, 134, 138), 16) / 10;
        fullBuf(result, "过流门限：", String.format("%.1f", overThreshold) + " m³/h");

        fullBuf(result, "错峰系数：", Integer.parseInt(StringUtils.substring(data, 138, 140), 16));

        fullBuf(result, "微小流报警使能：", enableFormat(data.substring(140, 142)));

        double maximumReserve = (double)Integer.parseInt(StringUtils.substring(data, 142, 146), 16) / 100;
        fullBuf(result, "最大预留量：", String.format("%.2f", maximumReserve) + " m³");

        return result.toString();
    }

    /**
     * 渲染状态
     * @param data
     * @return
     */
    private String readerState(String data) {
        data = data.substring(8);
        String state1 = data.substring(0, 2);
        String state2 = data.substring(2, 4);

        StringBuffer result = new StringBuffer();
        result.append(getState1().get(state1))
                .append("\n").append("\n")
                .append("温补状态:" )
                .append(getState2().get(state2));
        return result.toString();
    }
    /**
     * 状态1
     * @return
     */
    private Map<String, String> getState1() {
        String errorInfo = "{\"24\": \"表状态: 防拆功能启动 / 出厂状态\"," +
                "\"20\": \"状态: 防拆功能启动 / 未出厂状态\"," +
                "\"04\": \"状态: 防拆功能关闭 / 出厂状态\"," +
                "\"00\": \"状态: 防拆功能关闭 / 未出厂状态\"}";
        return JSONObject.parseObject(errorInfo, Map.class);
    }
    /**
     * 状态2
     * @return
     */
    private Map<String, String> getState2() {
        String errorInfo = "{\"30\": \"温度补偿 / 全补\", \"20\": \"全补\"," +
                "\"50\": \"温度补偿 / 正补\", \"40\": \"正补\"," +
                "\"10\": \"温度补偿 / 不补\", \"00\": \"不补\"," +
                "\"70\": \"温度补偿 / 设定值补偿\", \"60\": \"设定值补偿\"}";
        return JSONObject.parseObject(errorInfo, Map.class);
    }

    /**
     * 渲染温补数据
     * @return
     */
    private String readerRemovingData(String data) {

        if (data.length() <= 8) return "普通表";

        data = data.substring(8);

        StringBuffer result = new StringBuffer();
        result.append("工况累计量: ")
                .append(HexUtils.getFormatDouble(
                        Integer.parseInt(data.substring(0, 8), 16), 1))
                .append("m³").append("\n").append("\n");
        result.append("标况累计量: ")
                .append(HexUtils.getFormatDouble(
                        Integer.parseInt(data.substring(8, 16), 16), 1))
                .append("m³").append("\n").append("\n");
        result.append("温度: ")
                .append(HexUtils.getFormatDouble(
                        Integer.parseInt(data.substring(16, 20), 16), 2))
                .append("℃").append("\n").append("\n");
        result.append("标准压力值: ")
                .append(HexUtils.getFormatDouble(
                        Integer.parseInt(data.substring(20, 28), 16), 3))
                .append("kPa").append("\n").append("\n");
        result.append("设定压力值: ")
                .append(HexUtils.getFormatDouble(
                        Integer.parseInt(data.substring(28, 36), 16), 3))
                .append("kPa").append("\n").append("\n");
        result.append("流量系数: ")
                .append(Integer.parseInt(data.substring(36, 38), 16));
        return result.toString();
    }

    /**
     * 渲染读版本/锂电电压
     * @param data
     * @return
     */
    private String readerLithiumVoltage(String data) {

        StringBuffer result = new StringBuffer();
        data = data.substring(8);

        result.append("硬件版本: ")
                .append(data.substring(0, 4))
                 .append("\n").append("\n");
        result.append("软件版本: ")
                .append(data.substring(4, 8))
                .append("\n").append("\n");
        result.append("锂电电压: ")
                .append(HexUtils.getFormatDouble(
                        Integer.parseInt(data.substring(12, 16), 16), 3))
                .append("V");

        return result.toString();
    }

    private String readerClearE1Error(String data) {

        if (StringUtils.equals("9000", data.substring(2,6)))
            return "清除E-1错误成功";
        return "清除E-1错误失败";
    }
    private void fullBuf(StringBuffer buf, String title, Object data) {
        buf.append(title)
                .append(data)
                .append("\n");
    }
    private String enableFormat(String data) {
        if (StringUtils.equals("00", data)) return "禁用";
        if (StringUtils.equals("01", data)) return "开启";
        return data;
    }
}
